<template>
  <MainContainer class="p-5">
    <MyQuery
      v-model:params="params"
      :options="queryOptions"
      @query="handleQuery"
      @reset="handleReset"
    ></MyQuery>
    <div class="flex">
      <el-button @click="changeStatus()">修改状态</el-button>
      <el-button @click="handleLast()">返回上级</el-button>
      <el-button @click="exportTable()">导出数据</el-button>
    </div>
    <MyTable
      v-loading="loading"
      class="my-2"
      :data="list"
      :columns="columns"
      :is-show-selection="true"
      @confirm="handleConfirm"
    ></MyTable>
    <el-dialog
      v-model="dialogVisible"
      center
      title="修改状态数据"
      width="30%"
      :before-close="handleClose"
    >
      <el-select
        v-model="statusValue"
        class="w-full"
        placeholder="请选择状态"
        size="large"
      >
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleConfirmStatus">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </MainContainer>
</template>
<script setup lang="jsx">
import * as XLSX from "xlsx";
import MyQuery from "@/components/MyQuery.vue";
import MyTable from "@/components/MyTable.vue";
import MainContainer from "@/components/MainContainer.vue";
import { ElMessageBox, ElMessage } from "element-plus";
import {
  getCustomFormData,
  getCustomFormByKey,
  setCustomFormDataStatus,
} from "@/api/footform/custom-form";
import { useRoute, useRouter } from "vue-router";
import { ref, reactive } from "vue";
import parseTime from "@/utils/parseTime.js";

let route = useRoute();

const loading = ref(false);

const params = ref(getDefaultParams());
function getDefaultParams() {
  const { newParams } = getCustomFormData({ formKey: route.query.key });
  return Object.assign(
    { formKey: route.query.key, page: 1, limit: 10 },
    newParams
  );
}

const queryOptions = [
  {
    prop: "status",
    placeholder: "数据状态",
    customRender() {
      return (
        <el-select class="w-full">
          <el-option value={0} label="未处理" />
          <el-option value={1} label="处理中" />
          <el-option value={2} label="已处理" />
        </el-select>
      );
    },
  },
  {
    prop: "createTime",
    label: "任务执行时间",
    customRender() {
      return (
        <el-date-picker type="datetime" value-format="YYYY-MM-DD HH:mm:ss" />
      );
    },
  },
];

let columns = ref([]);

const list = ref([]);
const total = ref(0);
// 获取数据列表
async function handleQuery() {
  columns.value = [
    {
      prop: "id",
      label: "编号",
    },
    {
      prop: "status",
      label: "数据状态",
      formatter(row) {
        const { status } = row;
        switch (status) {
          case 0:
            return "未处理";
          case 1:
            return "处理中";
          case 2:
            return "已处理";
          default:
            break;
        }
      },
    },
    {
      prop: "createTime",
      label: "创建时间",
      formatter(row) {
        const date = new Date(row.createTime);
        return parseTime(date);
      },
    },
  ];
  list.value = [];
  loading.value = true;
  try {
    const {
      data: { list: formData = [] },
      total: listTotal,
    } = await getCustomFormData(params.value);

    const { data } = await getCustomFormByKey(route.query.key);
    const listData = JSON.parse(data.structure);

    loading.value = false;
    listData.forEach((item) => {
      columns.value.push({ prop: item.title, label: item.title });
    });
    formData.forEach((item, i) => {
      list.value.push(JSON.parse(item.originalData));
      list.value[i].status = item.status;
      list.value[i].createTime = item.createTime;
      list.value[i].id = item.id;
    });
    total.value = listTotal;
    titleArr.value = Object.keys(list.value[0]);
  } catch {
    loading.value = false;
  }
}

// 导出数据
const titleArr = ref([]);
function exportExcel(json, name, titleArr, sheetName) {
  let data = [];
  let keyArray = [];
  const getLength = function (obj) {
    var count = 0;
    for (let i in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, i)) {
        count++;
      }
    }
    return count;
  };
  for (const key1 in json) {
    if (Object.prototype.hasOwnProperty.call(json, key1)) {
      const element = json[key1];
      var rowDataArray = [];
      for (const key2 in element) {
        if (Object.prototype.hasOwnProperty.call(element, key2)) {
          const element2 = element[key2];
          rowDataArray.push(element2);
          if (keyArray.length < getLength(element)) {
            keyArray.push(key2);
          }
        }
      }
      data.push(rowDataArray);
    }
  }
  // keyArray为英文字段表头
  data.splice(0, 0, keyArray, titleArr);
  const ws = XLSX.utils.aoa_to_sheet(data);
  const wb = XLSX.utils.book_new();
  // 此处隐藏英文字段表头
  var wsrows = [{ hidden: true }];
  ws["!rows"] = wsrows;
  XLSX.utils.book_append_sheet(wb, ws, sheetName);
  XLSX.writeFile(wb, name + ".xlsx");
}

function exportTable() {
  exportExcel(list.value, "test", titleArr.value, "sheetName");
}

//重置查询
async function handleReset() {
  params.value = getDefaultParams();
  handleQuery();
}

//选择数据修改状态
let statusIds;
const flag = ref(false);
function handleConfirm(val) {
  if (val.length === 1) {
    statusIds = String(val[0].id);
  } else {
    statusIds = "";
    val.forEach((element) => {
      statusIds += String(element.id) + ",";
    });
    statusIds = statusIds.slice(0, statusIds.length - 1);
  }
  if (val.length > 0) {
    flag.value = true;
  } else {
    flag.value = false;
  }
  changeStatusList.ids = [];
  changeStatusList.status = 0;
  val.map((i) => {
    changeStatusList.ids.push(i.id);
    changeStatusList.status = i.status;
  });
}

const statusValue = ref(null);

const options = [
  {
    value: 0,
    label: "未处理",
  },
  {
    value: 1,
    label: "处理中",
  },
  {
    value: 2,
    label: "已处理",
  },
];

const dialogVisible = ref(false);

function changeStatus() {
  dialogVisible.value = true;
}

const changeStatusList = reactive({
  ids: [],
  status: null,
});

//提交状态数据
async function handleConfirmStatus() {
  changeStatusList.status = statusValue.value;
  if (flag.value) {
    await ElMessageBox.confirm("确定修改状态数据吗?", "Warning", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        setCustomFormDataStatus(changeStatusList);
        ElMessage({
          type: "success",
          message: "已修改",
        });
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "已取消",
        });
      });
  } else {
    ElMessage({
      type: "warning",
      message: "请选择一条数据",
      showClose: true,
    });
  }
  dialogVisible.value = false;
  statusValue.value = null;
  handleQuery();
}

function handleClose() {
  dialogVisible.value = false;
  statusValue.value = null;
}

let router = useRouter();
function handleLast() {
  router.back();
}

handleQuery();
</script>
